/**
 * Created by lk on 17/6/4.
 */
import axios from "@/utils/request";
import { parseDate, formatDate } from "./common";
import base from "../config/base";
import async from "async";

export function server_request(url, data, method) {
  method = method || "post";
  var obj = {
    url: url,
    method: method
  };

  // 处理数据自动格式化
  for (var key in data) {
    if (data[key] instanceof Date) {
      data[key] = formatDate(data[key], "yyyy-MM-dd hh:mm:ss");
    }else if (data[key] instanceof Array) {
      data[key] = data[key].join(base.array_split_chat);
    } else if ( data[key] instanceof Object) {
      data[key] = JSON.stringify(data[key]);
    }
  }

  obj[method == "post" ? "data" : "params"] = data;
  return axios(obj);
}

// 上传文件
export function server_upload_file(url, formdata, progress) {
  return axios({
    url: url,
    method: "post",
    data: formdata,
    onUploadProgress: e => {
      let percent = Math.round((e.loaded / e.total) * 100);
      typeof progress == "function" && progress({ percent: percent });
    }
  });
}
